<template>
  <view class="dishes-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <text class="back-text">返回</text>
        </view>
        <view class="title">
          <text class="title-text">选择菜品</text>
        </view>
        <view class="save-btn" @click="saveDishes">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-box">
        <image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
        <input
          type="text"
          v-model="searchKeyword"
          placeholder="搜索菜品名称"
          class="search-input"
          @input="onSearchInput"
        />
      </view>
    </view>

    <!-- 菜品列表 -->
    <scroll-view class="dish-list" scroll-y="true">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="filteredDishList.length === 0" class="empty-state">
        <image src="/static/image/no_permission.png" class="empty-icon" mode="aspectFit"></image>
        <text class="empty-text">暂无菜品</text>
        <text class="empty-desc">该供应商暂无可选菜品</text>
      </view>

      <!-- 菜品列表 -->
      <view v-else class="dish-list-container">
        <view v-for="(dish, index) in filteredDishList" :key="dish.id" class="dish-item">
          <view class="dish-info">
            <view class="dish-name">
              <text class="name-text">{{ dish.name }}</text>
            </view>
            <view class="dish-category">
              <text class="category-text">{{ dish.category }}</text>
            </view>
          </view>

          <view class="dish-price">
            <view class="price-info">
              <text class="price-label">官方参考价格</text>
              <text class="price-value">¥{{ dish.base_price }}</text>
            </view>
            <view v-if="dish.supplier_quoted_price" class="price-info">
              <text class="price-label">供应商报价</text>
              <text class="price-value quoted">¥{{ dish.supplier_quoted_price }}</text>
            </view>
          </view>

          <view class="dish-quantity">
            <text class="quantity-label">计划数量</text>
            <u-number-box input-width="120" :positive-integer="false" step="1" v-model="dish.planned_quantity"></u-number-box>
            <text class="unit-text">{{ dish.unit }}</text>
          </view>
          <view class="dish-remark">
            <text class="remark-label">备注</text>
            <view class="remark-input">
                <textarea
                    v-model="dish.planned_remark"
                    placeholder="请输入备注（选填）"
                    class="remark-field"
                    maxlength="200"
                    :show-confirm-bar="false"
                />
              <view class="char-count">
                <text class="count-text">{{ dish.planned_remark ? dish.planned_remark.length : 0 }}/200</text>
              </view>
            </view>
          </view>

        </view>
      </view>
    </scroll-view>

    <!-- 底部统计 -->
    <view class="bottom-stats">
      <view class="stats-info">
        <text class="stats-text">已选择 {{ selectedCount }} 道菜品</text>
      </view>
      <view class="stats-total">
        <text class="total-label">总价</text>
        <text class="total-value">¥{{ totalPrice }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import api from "../../config/api.js";

export default {
  data() {
    return {
      workorderId: '',
      loading: true,
      searchKeyword: '',
      dishList: [],

      // 采购单信息
      workorderInfo: {},

      // 已存在的菜单项
      existingMenuItems: []
    }
  },

  computed: {
    // 过滤后的菜品列表
    filteredDishList() {
      if (!this.searchKeyword) {
        return this.dishList;
      }
      return this.dishList.filter(dish => (dish.name && dish.name.includes(this.searchKeyword)) || dish.category && dish.category.includes(this.searchKeyword));

    },

    // 已选择的菜品数量
    selectedCount() {
      return this.dishList.filter(dish =>
        dish.planned_quantity && dish.planned_quantity > 0
      ).length;
    },

    // 总价
    totalPrice() {
      return this.dishList.reduce((total, dish) => {
        if (dish.planned_quantity && dish.planned_quantity > 0) {
          const price = dish.supplier_quoted_price || 0;
          return total + (price * dish.planned_quantity);
        }
        return total;
      }, 0).toFixed(2);
    }
  },

  onLoad(options) {
    this.$store.dispatch('getUserInfo')
    if (options.id) {
      this.workorderId = options.id;
      this.loadWorkorderInfo();
    }
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 加载采购单信息
    loadWorkorderInfo() {
      api.getDailyMenu(this.workorderId).then(response => {
        this.workorderInfo = response;
        this.loadDishList();
      }).catch(error => {
        console.error('加载采购单信息失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
    },

    // 加载菜品列表
    async loadDishList() {
      this.loading = true;

      try {
        // 获取菜品列表（基于月度比价项目）
        const params = {
          monthly_bidding_id: this.workorderInfo.monthly_bidding_id,
        };

        const dishResponse = await api.getDishList(params);
        this.dishList = (dishResponse || []).map(dish => ({
          ...dish,
          planned_quantity: 0,
          planned_remark: '',
        }));

        // 获取供应商报价信息
        await this.loadSupplierQuotes();

        // 加载已存在的菜单项
        await this.loadExistingMenuItems();

      } catch (error) {
        console.error('加载菜品列表失败:', error);
        uni.showToast({
          title: '加载菜品列表失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 加载供应商报价
    async loadSupplierQuotes() {
      try {
        const params = {
          monthly_bidding_id: this.workorderInfo.monthly_bidding_id,
          supplier_id: this.workorderInfo.supplier_id
        };

        const response = await api.getSupplierQuoteList(params);
        const quotes = response || [];
        const quoteMap = {};

        quotes.forEach(quote => {
          quoteMap[quote.dish_id] = quote.quoted_price;
        });

        // 将供应商报价信息合并到菜品列表中
        this.dishList = this.dishList.map(dish => ({
          ...dish,
          supplier_quoted_price: quoteMap[dish.id] || null
        }));

      } catch (error) {
        console.error('加载供应商报价失败:', error);
      }
    },

    // 加载已存在的菜单项
    async loadExistingMenuItems() {
      try {
        const response = await api.getDailyMenuItemList({
          daily_menu_id: this.workorderId
        });

        this.existingMenuItems = response || [];

        // 双向遍历，如果dailyMenuItem数据中已存在需要替换dish数据
        this.dishList = this.dishList.map(dish => {
          const existingItem = this.existingMenuItems.find(item => item.dish_id === dish.id);
          if (existingItem) {
            return {
              ...dish,
              planned_quantity: existingItem.planned_quantity || 0,
              actual_quantity: existingItem.actual_quantity || 0,
              actual_price: existingItem.actual_price || null,
              quality_rating: existingItem.quality_rating || null,
              remark: existingItem.remark || '',
              planned_remark: existingItem.planned_remark || '',
              menuItemId: existingItem.id, // 保存菜单项ID，用于后续更新
              isExisting: true // 标记为已存在的菜品
            };
          }
          return dish;
        });

        console.log('已加载菜单项:', this.existingMenuItems.length, '个');

      } catch (error) {
        console.error('加载已存在菜单项失败:', error);
      }
    },

    // 搜索输入
    onSearchInput() {
      // 实时搜索逻辑
    },

    // 减少数量
    decreaseQuantity(dish) {
      if (dish.planned_quantity > 0) {
        dish.planned_quantity--;
      }
    },

    // 增加数量
    increaseQuantity(dish) {
      dish.planned_quantity = (dish.planned_quantity || 0) + 1;
    },

    // 数量输入
    onQuantityInput(dish, event) {
      const value = parseInt(event.detail.value);
      if (isNaN(value) || value < 0) {
        dish.planned_quantity = 0;
      } else {
        dish.planned_quantity = value;
      }
    },

    // 保存菜品选择
    async saveDishes() {
      const selectedDishes = this.dishList.filter(dish => {
        if (dish.isExisting) {
          return dish
        } else {
          return  dish.planned_quantity && dish.planned_quantity >= 0
        }
        return false
      });

      if (selectedDishes.length === 0) {
        uni.showToast({
          title: '请至少选择一道菜品',
          icon: 'none'
        });
        return;
      }
      try {
        // 分离新增和更新的菜品
        const newDishes = selectedDishes.filter(dish => !dish.isExisting);
        const updateDishes = selectedDishes.filter(dish => dish.isExisting);

        // 处理新增菜品
        if (newDishes.length > 0) {
          const newMenuItems = newDishes.map(dish => ({
            daily_menu_id: this.workorderId,
            dish_id: dish.id,
            base_price: dish.base_price,
            supplier_quoted_price: dish.supplier_quoted_price || 0,
            planned_quantity: dish.planned_quantity,
            planned_remark: dish.planned_remark,
            status: 1 // 待采购状态
          }));

          await api.batchCreateDailyMenuItem(newMenuItems);
        }

        // 处理更新菜品
        if (updateDishes.length > 0) {
          await api.batchUpdateDailyMenuItem(updateDishes.map(item => {
            return {
              id: item.menuItemId,
              planned_quantity: item.planned_quantity,
              planned_remark: item.planned_remark,
              supplier_quoted_price: item.supplier_quoted_price || 0
            }
          }));
        }

        uni.showToast({
          title: `保存成功，新增${newDishes.length}个，更新${updateDishes.length}个`,
          icon: 'success'
        });

        // setTimeout(() => {
        //   uni.navigateBack();
        // }, 1000);

      } catch (error) {
        console.error('保存菜品失败:', error);
        uni.showToast({
          title: '保存失败：' + (error.message || '未知错误'),
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss">
.dishes-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

// 顶部导航
.header {
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .back-btn {
      .back-text {
        font-size: 32rpx;
        color: #666;
      }
    }

    .title {
      .title-text {
        font-size: 36rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .save-btn {
      .save-text {
        font-size: 32rpx;
        color: #FFC300;
        font-weight: 500;
      }
    }
  }
}

// 搜索栏
.search-section {
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 20rpx;

  .search-box {
    display: flex;
    align-items: center;
    background-color: #f8f8f8;
    border-radius: 24rpx;
    padding: 16rpx 24rpx;
    gap: 12rpx;

    .search-icon {
      width: 32rpx;
      height: 32rpx;
    }

    .search-input {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
  }
}

// 菜品列表
.dish-list {
  //height: calc(100vh - 300rpx);
}

// 加载状态
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;

  .loading-text {
    font-size: 28rpx;
    color: #666;
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  padding: 0 32rpx;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 32rpx;
    color: #999;
    margin-bottom: 16rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #ccc;
  }
}

.dish-list-container {
  padding: 0 32rpx;
}

.dish-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;

  .dish-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;

    .dish-name {
      .name-text {
        font-size: 32rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .dish-category {
      .category-text {
        font-size: 24rpx;
        color: #666;
        background-color: #e8e8e8;
        padding: 8rpx 16rpx;
        border-radius: 8rpx;
      }
    }
  }

  .dish-price {
    margin-bottom: 24rpx;

    .price-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .price-label {
        font-size: 26rpx;
        color: #666;
      }

      .price-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;

        &.quoted {
          color: #FF6B35;
          font-weight: 600;
        }
      }
    }
  }
  .dish-remark {
    .remark-label {
      display: block;
      font-size: 26rpx;
      color: #666;
      margin-bottom: 16rpx;
    }

    .remark-input {
      position: relative;

      .remark-field {
        width: 100%;
        font-size: 28rpx;
        color: #333;
        line-height: 1.5;
        height: 120rpx;
        padding: 16rpx;
        border: 1rpx solid #e8e8e8;
        border-radius: 8rpx;
        background-color: #fff;
      }

      .char-count {
        text-align: right;
        margin-top: 8rpx;

        .count-text {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }

  .dish-quantity {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .quantity-label {
      font-size: 26rpx;
      color: #666;
    }

    .quantity-input {
      display: flex;
      align-items: center;
      border: 1rpx solid #e8e8e8;
      border-radius: 8rpx;
      overflow: hidden;

      .quantity-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f5f5f5;

        .btn-text {
          font-size: 32rpx;
          color: #333;
          font-weight: 600;
        }
      }

      .quantity-field {
        width: 120rpx;
        height: 60rpx;
        text-align: center;
        font-size: 28rpx;
        color: #333;
        border: none;
        background-color: #fff;
      }
    }

    .unit-text {
      font-size: 26rpx;
      color: #666;
    }
  }
}

// 底部统计
.bottom-stats {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .stats-info {
    .stats-text {
      font-size: 20rpx;
      color: #666;
    }
  }

  .stats-total {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .total-label {
      font-size: 28rpx;
      color: #666;
    }

    .total-value {
      font-size: 36rpx;
      color: #FF6B35;
      font-weight: 600;
    }
  }
}
</style>
